//
//  YWMaterialListTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWMaterialListTableViewController.h"
#import "YWApplyMaterialTableViewController.h"
#import "YWMaterialApplyTableViewController.h"
#import "YWMaterialStockOutTableViewController.h"
#import "YWMaterialReturnBackTableViewController.h"
#import "YWScanEquipmentNotMatchVC.h"
#import "YWMaterialNumbleCertainTableViewController.h"

#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "DLTabedSlideView.h"
#import "DLFixedTabbarView.h"
#import "Masonry.h"
#import "MBProgressHUD.h"
#import "YWQrcodeManager.h"
#import "YWCommonTool.h"

#import "YWMaterialApply.h"
#import "YWMaterialStockOut.h"
#import "YWMaterialManager.h"
//#import "YWUnReadCount.h"
//#import "YWEwinManager.h"

@interface YWMaterialListTableViewController ()<DLTabedSlideViewDelegate>
@property (nonatomic, weak) DLTabedSlideView* tabedSlideView;
@property (nonatomic, strong) UIButton *scanButton;
//@property (nonatomic, strong) UIButton *noScanButton;

@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) NSArray * scanQrcodeArray;
@end

@implementation YWMaterialListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申领";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
    target:self action:@selector(handleApplyMaterialAction:)];
    
    [self autoLayoutTableViewTitleView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 开启
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (DLTabedSlideView*)tabedSlideView
{
    if (!_tabedSlideView) {
        DLTabedSlideView* tabedSlideView = [[DLTabedSlideView alloc] init];
        tabedSlideView.delegate = self;
        tabedSlideView.baseViewController = self;
        tabedSlideView.tabItemNormalColor = [UIColor blackColor];
        tabedSlideView.tabItemSelectedColor = [UIColor customRedColor];
        tabedSlideView.tabbarTrackColor = [UIColor customRedColor];
        tabedSlideView.backgroundColor = [UIColor whiteColor];
        //YWUnReadCount *totalCount = [[YWEwinManager shareManager] totalCount];
        //NSString *title = totalCount.materialTotal>0?[NSString stringWithFormat:@"申请单(%ld)",(long)totalCount.materialTotal]:@"申请单";
        DLTabedbarItem * noReceipientItem = [DLTabedbarItem itemWithTitle:@"申请单" image:nil selectedImage:nil];
        DLTabedbarItem * receipientItem = [DLTabedbarItem itemWithTitle:@"领用单" image:nil selectedImage:nil];
        DLTabedbarItem * returnItem = [DLTabedbarItem itemWithTitle:@"归还单" image:nil selectedImage:nil];
        tabedSlideView.tabbarItems = @[noReceipientItem, receipientItem, returnItem ];
        [tabedSlideView buildTabbar];
        tabedSlideView.selectedIndex = (_currentIndex==2 || _currentIndex==1) ? _currentIndex : 0;
        [self.view addSubview:tabedSlideView];
        _tabedSlideView = tabedSlideView;
    }
    return _tabedSlideView;
}

- (void)autoLayoutTableViewTitleView{
    [self.tabedSlideView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.mas_equalTo(self.view.mas_top);//.offset(64);
        make.left.mas_equalTo(self.view.mas_left);
        make.height.mas_equalTo(self.view.mas_height);//.offset(-64);
        make.width.mas_equalTo(self.view.mas_width);
    }];
//    [self.view addSubview:self.noScanButton];
    [self.view addSubview:self.scanButton];
}


- (UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        //[scanButton setImage:[UIImage imageNamed:@"temp_scanButton"] forState:UIControlStateNormal];
        //scanButton.layer.masksToBounds = YES;
        [button setTitle:@"扫码" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(handleScanButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH, KbottomViewH);
        _scanButton = button;
    }
    return _scanButton;
}


- (void)handleScanButtonEvent:(UIButton*)sender{
    [[YWQrcodeManager shareManager]clickMaterialScanWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        self.scanQrcodeArray = [qrcodeId componentsSeparatedByString:@","];
        if ([self.scanQrcodeArray containsObject:@"material_stock_out"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                        NSInteger stockOutId = [self.scanQrcodeArray[3] integerValue];
                        [self qrcodeSuccessRequestApplyAndMaterialStockOutWithStockOutId:stockOutId];
                    }];
                });
        }else if ([self.scanQrcodeArray containsObject:@"material_return"]){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                        NSInteger returnId = [self.scanQrcodeArray[3] integerValue];
                        [self qrcodeSuccessRequestReturnWithReturnId:returnId];
                    }];
                });
        }else{
            YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
            senmVC.showContent = @"非物料二维码，请确认！";
            [qrCodeReaderViewController.navigationController pushViewController:senmVC animated:YES];
        }
        
    }];
}

- (void)qrcodeSuccessRequestApplyAndMaterialStockOutWithStockOutId:(NSInteger)stockOutId{
    [self.HUD show:YES];
    NSInteger creatorId = [self.scanQrcodeArray[1] integerValue];
    [[YWMaterialManager shareManager] scanMaterialReceipientQrcodeWithStockOutId:stockOutId creatorId:creatorId isScan:YES WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            YWMaterialStockOut * stockOut =
            [[YWMaterialManager shareManager] materialReceipientWithMaterialReceipientId:stockOutId];
            //新要求改为跳转页面，跳转时要把self.scanStockOut传过去
            YWMaterialNumbleCertainTableViewController * certainVC = [YWMaterialNumbleCertainTableViewController new];
            certainVC.stockOut = stockOut;
            certainVC.scanStockOut = self.scanQrcodeArray;
            [self.navigationController pushViewController:certainVC animated:YES];
        }
    }];
}

- (void)qrcodeSuccessRequestReturnWithReturnId:(NSInteger)returnId
{
    [self.HUD show:YES];
    NSInteger creatorId = [self.scanQrcodeArray[1] integerValue];
    [[YWMaterialManager shareManager] scanMaterialReturnQrcodeWithReturnId:returnId creatorId:creatorId isScan:YES WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            YWMaterialReturn * materialReturn = [[YWMaterialManager shareManager] materialReturnWithMaterialReturnId:returnId];
            //改为跳转页面，要把self.scanReturnArray传过去
            YWMaterialNumbleCertainTableViewController * certainVC = [YWMaterialNumbleCertainTableViewController new];
            certainVC.returnBack = materialReturn;
            certainVC.scanReturn = self.scanQrcodeArray;
            [self.navigationController pushViewController:certainVC animated:YES];
        }
    }];
}

- (NSInteger)numberOfTabsInDLTabedSlideView:(DLTabedSlideView*)sender
{
    return self.tabedSlideView.tabbarItems.count;
}

- (UIViewController*)DLTabedSlideView:(DLTabedSlideView*)sender controllerAt:(NSInteger)index
{
    switch (index) {
        case 0: {
            YWMaterialApplyTableViewController * noReceipientVC = [[YWMaterialApplyTableViewController alloc] init];
            return noReceipientVC;
        }
        case 1: {
            YWMaterialStockOutTableViewController * receipientVC = [[YWMaterialStockOutTableViewController alloc] init];
            return receipientVC;
        }
        case 2: {
            YWMaterialReturnBackTableViewController * returnVC = [[YWMaterialReturnBackTableViewController alloc] init];
            return returnVC;
        }
            
        default:
            return nil;
    }
}
#pragma mark - buttonAction
- (void)handleApplyMaterialAction:(id)sender{
    YWApplyMaterialTableViewController * applyMaterialVC = [[YWApplyMaterialTableViewController alloc] init];
    [self.navigationController pushViewController:applyMaterialVC animated:YES];
}
@end
